package com.itheima.leyou.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.leyou.po.Category;
import com.itheima.leyou.po.CategoryBrand;
import com.itheima.leyou.mapper.CategoryMapper;
import com.itheima.leyou.service.CategoryBrandService;
import com.itheima.leyou.service.CategoryService;
import com.leyou.item.dto.CategoryDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private CategoryBrandService categoryBrandService;


    /**
     * 根据父id查询子分类信息
     * @param pid
     * @return
     */
    @Override
    public List<CategoryDTO> queryCategorysByPid(Long pid) {

        List<Category> categoryList = this.query()
                .eq(null!=pid,"parent_id", pid).list();
        return CategoryDTO.convertEntityList(categoryList);
    }

    /*
     * 根据分类ids集合查询分类集合
     * @param ids
     * @return
     */
    @Override
    public List<CategoryDTO> queryCategoryByIds(List<Long> ids) {
        return CategoryDTO.convertEntityList(this.listByIds(ids));

    }

    /**
     * 根据分类id查询对应的分类信息
     * @param id
     * @return
     */
    @Override
    public CategoryDTO queryCategoryById(Long id) {
       return baseMapper.queryCategoryById(id);
    }

    /**
     * 根据品牌 id查询分类
     * @param bid
     * @return
     */
    @Override
    public List<CategoryDTO> queryCategoryByBrandId(Long bid) {
        //根据品牌id查询中间表，得到categoryBrandIds的集合
        List<CategoryBrand> categoryBrandIds = categoryBrandService.query()
                .eq("brand_id", bid)
                .list();
        //将中间表中查询到的ids转化为dto格式
        List<Long> categoryIds = categoryBrandIds
                .stream()
                .map(CategoryBrand::getCategoryId)
                .collect(Collectors.toList());

        return this.queryCategoryByIds(categoryIds);

    }
}
